package com.uniriho.lxr0811_7300_bl.ble

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattService
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.uniriho.lxr0811_7300_bl.base.BaseApplication
import com.uniriho.lxr0811_7300_bl.base.Constant
import com.uniriho.lxr0811_7300_bl.ui.activity.HomeActivity
import com.uniriho.lxr0811_7300_bl.utils.DataTo
import java.util.UUID

class BleCon {
    companion object{
        private lateinit var liveData: MutableLiveData<String>
        private val TAG:String = "BleCon"
        private var isConnected = false
        private lateinit var mBluetoothGatt: BluetoothGatt
        private lateinit var  mConText:Context

        val mBluetoothGattCallback = object : BluetoothGattCallback() {
            @SuppressLint("MissingPermission")
            override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
                super.onConnectionStateChange(gatt, status, newState)
                var dev = gatt!!.device
                if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothGatt.STATE_CONNECTED) {
                    isConnected = true
                    val discoverServicesState: Boolean = gatt.discoverServices()
                    Log.e(TAG, "启动服务状态==$discoverServicesState")
                    mConText.startActivity(Intent(mConText, HomeActivity::class.java))
                } else {
                    isConnected = false
                    closeConn()
                }
                Log.e(
                    TAG,
                    String.format(
                        if (status == 0) (if (newState == 2) "与[%s]连接成功" else "与[%s]连接断开") else "与[%s]连接出错,错误码:$status",
                        dev
                    )
                )
            }

            //发现服务
            override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
                super.onServicesDiscovered(gatt, status)
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    gatt!!.services.forEach {
                        var uuid = it.uuid.toString()
                        Log.e(TAG, "onServicesDiscovered==$uuid")
                    }
                }
            }

            @SuppressLint("MissingPermission")
            override fun onCharacteristicRead(
                gatt: BluetoothGatt,
                characteristic: BluetoothGattCharacteristic,
                status: Int
            ) {
                super.onCharacteristicRead(gatt, characteristic, status)
                var name = gatt!!.device.name
                var address = gatt.device.address
                var Characteristic= DataTo.byteArrayToHexStr(characteristic.value)!!
                Log.e(TAG, "onCharacteristicRead==$name:$address:$Characteristic")
                liveData.postValue(Characteristic)
            }

            @SuppressLint("MissingPermission")
            override fun onCharacteristicWrite(
                gatt: BluetoothGatt?,
                characteristic: BluetoothGattCharacteristic?,
                status: Int
            ) {
                super.onCharacteristicWrite(gatt, characteristic, status)

                var name = gatt!!.device.name
                var address = gatt.device.address
                var Characteristic = characteristic!!.value.toString()
                Log.e(TAG, "onCharacteristicWrite==$name:$address:$Characteristic")
            }

            @SuppressLint("MissingPermission")
            override fun onCharacteristicChanged(
                gatt: BluetoothGatt,
                characteristic: BluetoothGattCharacteristic,
                value: ByteArray
            ) {
                super.onCharacteristicChanged(gatt, characteristic, value)
                var name = gatt!!.device.name
                var address = gatt.device.address
                var Characteristic = characteristic!!.value.toString()
                Log.e(TAG, "onCharacteristicChanged==$name:$address:$Characteristic")
            }

            @SuppressLint("MissingPermission")
            override fun onDescriptorRead(
                gatt: BluetoothGatt,
                descriptor: BluetoothGattDescriptor,
                status: Int,
            ) {
                super.onDescriptorRead(gatt, descriptor, status)
                var name = gatt!!.device.name
                var address = gatt.device.address
                var Characteristic = descriptor!!.value.toString()
                Log.e(TAG, "onCharacteristicChanged==$name:$address:$Characteristic")
            }

            @SuppressLint("MissingPermission")
            override fun onDescriptorWrite(
                gatt: BluetoothGatt?,
                descriptor: BluetoothGattDescriptor?,
                status: Int
            ) {
                super.onDescriptorWrite(gatt, descriptor, status)
                var name = gatt!!.device.name
                var address = gatt.device.address
                var Characteristic = descriptor!!.value.toString()
                Log.e(TAG, "onCharacteristicChanged==$name:$address:$Characteristic")
            }
        }

        @SuppressLint("MissingPermission")
        fun DevConnect(context: Context, dev: BluetoothDevice?){
            this.mConText = context
            mBluetoothGatt =
                dev!!.connectGatt(mConText, false, mBluetoothGattCallback, BluetoothDevice.TRANSPORT_LE)
            Log.e(TAG, "与${dev.address}开始连接")
        }

        // 注意：连续频繁读写数据容易失败，读写操作间隔最好200ms以上，或等待上次回调完成后再进行下次读写操作！
        // 读取数据成功会回调->onCharacteristicChanged()
        @SuppressLint("MissingPermission")
        fun read(liveData: MutableLiveData<String>) {
            this.liveData = liveData
            val service: BluetoothGattService = getGattService(Constant.UUID_SERVICE)!!
            val characteristic =
                service.getCharacteristic(Constant.UUID_CHAR_READ_NOTIFY) //通过UUID获取可读的Characteristic
            mBluetoothGatt.readCharacteristic(characteristic)
        }

        /**
         * 写数据
         *  @param data
         */
        fun writeCmd(data: String) {
            val hexStrToByteArray: ByteArray = DataTo.hexStrToByteArray(data)!!
            bleNotifyDevice(hexStrToByteArray)
        }

        // 获取Gatt服务
        private fun getGattService(uuid: UUID): BluetoothGattService? {
            if (!isConnected) {
                BaseApplication.toast("没有连接", 0)
                return null
            }
            val service = mBluetoothGatt.getService(uuid)
            if (service == null) BaseApplication.toast("没有找到服务UUID=$uuid", 0)
            return service
        }

        /**
         * 发送通知
         */
        @SuppressLint("MissingPermission")
        private fun bleNotifyDevice(data: ByteArray) {
            try {
                val service = getGattService(Constant.UUID_SERVICE)
                if (service != null) {
                    val characteristic =
                        service.getCharacteristic(Constant.UUID_CHAR_WRITE) //通过UUID获取可写的Characteristic
                    characteristic.value = data //单次最多20个字节
                    mBluetoothGatt.writeCharacteristic(characteristic)
                }
            } catch (e: Exception) {
                Log.e(TAG, e.toString())
            }
        }

        @SuppressLint("MissingPermission")
        private fun closeConn() {
            mBluetoothGatt!!.disconnect()
            mBluetoothGatt!!.close()
        }
    }
}